package com.uzai.console.service.locallive.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.uzai.common.enums.OrderReStatusEnum;
import com.uzai.common.enums.OrderStatusEnum;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.dto.feign.mtorder.MtOrderPullDto;
import com.uzai.console.dto.feign.mtorder.MtOrderSettledDto;
import com.uzai.console.dto.locallive.mtorder.MtFindUnReceicedDto;
import com.uzai.console.dto.locallive.mtorder.MtOrderDownLoadDto;
import com.uzai.console.dto.locallive.tlbtoken.TlbTokenQuery;
import com.uzai.console.entity.MtOrder;
import com.uzai.console.entity.TlbToken;
import com.uzai.console.mapper.MtOrderMapper;
import com.uzai.console.mapper.TlbTokenMapper;
import com.uzai.console.para.MtOrderRemoteApiPara;
import com.uzai.console.service.feign.MtOrderFeignService;
import com.uzai.console.service.locallive.MtOrderSyncService;
import com.uzai.console.service.remoteapi.MtOrderRemoteApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther: lucher
 * @Date: 2019/11/27 11:23
 * @Description:
 */
@Service
public class MtOrderSyncServiceImpl implements MtOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(MtOrderSyncServiceImpl.class);

    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private TlbTokenMapper tlbTokenMapper;
    @Autowired
    private MtOrderRemoteApiService mtOrderRemoteApiService;
    @Autowired
    private MtOrderFeignService mtOrderFeignService;

    /**
     * 手动下载单个联盟订单
     *
     * @param mtOrderDownLoadDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void downloadOrder(MtOrderDownLoadDto mtOrderDownLoadDto, Long mtTokenId) {
        //调用订单业务库服务器
        //调用订单业务库服务器
        TlbToken tlbToken = tlbTokenMapper.selectById(mtTokenId, mtOrderDownLoadDto.getMerId());
        if (tlbToken != null) {
            //美团联盟
            MtOrderPullDto mtOrderPullDto = new MtOrderPullDto();
            mtOrderPullDto.setTokenId(tlbToken.getAppId());
            mtOrderPullDto.setPlatform("mt");
            mtOrderPullDto.setStartTime(mtOrderDownLoadDto.getQueryStartTime());
            mtOrderPullDto.setEndTime(mtOrderDownLoadDto.getQueryEndTime());
            //时间类型 0订单库入库时间， 1订单库更新时间， 2订单创建时间， 3订单最后更新时间， 4订单付款时间， 5订单完成（收货）时间， 6订单结算时间，7订单维权创建时间，8订单维权完成时间")
            Integer timeType_lm = 2;
            mtOrderPullDto.setTimeType(timeType_lm);
            //请求订单拉取接口
            mtOrderFeignService.pull(mtOrderPullDto);
        }
    }

    /**
     * 异步手动下载多个淘宝联盟订单
     *
     * @param mtOrderDownLoadDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Async("taskExecutor")
    @Override
    public void downloadOrderListSync(MtOrderDownLoadDto mtOrderDownLoadDto) {

        //调用订单业务库服务器
        TlbTokenQuery tlbTokenQuery = new TlbTokenQuery();
        tlbTokenQuery.setType("mt");
        List<TlbToken> tlbTokenList = tlbTokenMapper.findByList(tlbTokenQuery);
        if (tlbTokenList != null && tlbTokenList.size() > 0) {
            for (TlbToken token : tlbTokenList) {
                try {
                    downloadOrder(mtOrderDownLoadDto, token.getId());
                } catch (Exception e) {
                    logger.error("-------downloadOrderListSync is error mtTokenId={}, error={}", token.getId(), e.getMessage());
                }
            }
        }

        //调用订单拉取库服务器
        MtOrderRemoteApiPara mtOrderRemoteApiPara = new MtOrderRemoteApiPara();
        mtOrderRemoteApiPara.setQueryStartTime(mtOrderDownLoadDto.getQueryStartTime());
        mtOrderRemoteApiPara.setQueryEndTime(mtOrderDownLoadDto.getQueryEndTime());
        mtOrderRemoteApiService.remoteDownload(mtOrderRemoteApiPara);
        logger.info("---调用CPS接口下载美团订单----para={}", JSONObject.toJSONString(mtOrderRemoteApiPara));

    }

    /**
     * 远程调用订单库API，手动更新单个订单
     *
     * @param mtOrder
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrder(MtOrder mtOrder) {

        //判断订单存在或者已删除
        if (mtOrder == null) {
            return;
        }

//        //调用订单拉取库服务器
//        MtOrderPullDto mtOrderPullDto_lm = new MtOrderPullDto();
//        mtOrderPullDto_lm.setPlatform("mt");
//        mtOrderPullDto_lm.setStartTime(mtOrder.getPaydt()-1);
//        mtOrderPullDto_lm.setEndTime(mtOrder.getPaydt() + 1);
//        //时间类型 0订单库入库时间， 1订单库更新时间， 2订单创建时间， 3订单最后更新时间， 4订单付款时间， 5订单完成（收货）时间， 6订单结算时间，7订单维权创建时间，8订单维权完成时间")
//        Integer timeType_lm = 4;
//        mtOrderPullDto_lm.setTimeType(timeType_lm);

        //调用订单拉取库服务器
        MtOrderRemoteApiPara mtOrderRemoteApiPara = new MtOrderRemoteApiPara();
        mtOrderRemoteApiPara.setQueryStartTime(mtOrder.getPaydt() - 1);
        mtOrderRemoteApiPara.setQueryEndTime(mtOrder.getPaydt() + 1);
        mtOrderRemoteApiPara.setChildOrderNo(mtOrder.getChildOrderNo());
        mtOrderRemoteApiService.remoteDownload(mtOrderRemoteApiPara);
        logger.info("---调用CPS接口下载美团订单----para={}", JSONObject.toJSONString(mtOrderRemoteApiPara));

    }

    @Override
    public void uploadMtOrderSettingSync(Long merId, int day, int status, List<Integer> sourceStatus) {
        if (merId == null) {
            return;
        }
        //设置结束时间为day天前
        int endTime = DateUtil.getNowTime() - day * 24 * 3600;
        mtOrderMapper.updateStatusPayCompleteToSettle(null, endTime, null, merId, status, sourceStatus);
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderUnReceivedListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        mtFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        mtFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(0);
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderUnReceivedListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderFreezedListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        mtFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        mtFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（已收货）
        mtFindUnReceicedDto.setStatus(1);
        List<MtOrder> mtOrderList = mtOrderMapper.findFreezedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderFreezedListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderUnReceivedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(0);
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderUnReceivedListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前未收货订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderUnReceivedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(0);
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    //订单状态为0-付款状态时，才能确认收货
                    if (mtOrder.getStatus() == 0) {
                        //调用确认收货接口
                        MtOrderSettledDto mtOrderSettledDto = new MtOrderSettledDto();
                        mtOrderSettledDto.setMerId(mtOrder.getMerId());
                        mtOrderSettledDto.setOrderId(mtOrder.getParentOrderNo());
                        mtOrderSettledDto.setChildOrderId(mtOrder.getChildOrderNo());
                        UzaiRespVo<Object> result = mtOrderFeignService.settled(mtOrderSettledDto);
                        logger.info("---发送修改美团订单确认收货-para={}, result={}", JSONObject.toJSONString(mtOrderSettledDto), JSONObject.toJSONString(result));
                    }
                } catch (Exception e) {
                    logger.error("-------updateMtOrderUnReceivedListSync_settle is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }


    /**
     * 远程调用订单库API，更新day天前已冻结的订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderFreezedListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        mtFindUnReceicedDto.setStatus(1);
        List<MtOrder> mtOrderList = mtOrderMapper.findFreezedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderFreezedListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前已冻结订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderFreezedListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（已收货）
        mtFindUnReceicedDto.setStatus(1);
        List<MtOrder> mtOrderList = mtOrderMapper.findFreezedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    //先修改订单状态为0-付款状态时，才能确认收货
                    mtOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    mtOrder.setUpdateTime(DateUtil.getNowTime());
                    mtOrderMapper.updateStatus(mtOrder);
                    //调用确认收货接口
                    MtOrderSettledDto mtOrderSettledDto = new MtOrderSettledDto();
                    mtOrderSettledDto.setMerId(mtOrder.getMerId());
                    mtOrderSettledDto.setOrderId(mtOrder.getParentOrderNo());
                    mtOrderSettledDto.setChildOrderId(mtOrder.getChildOrderNo());
                    UzaiRespVo<Object> result = mtOrderFeignService.settled(mtOrderSettledDto);
                    logger.info("---发送修改美团订单确认收货-para={}, result={}", JSONObject.toJSONString(mtOrderSettledDto), JSONObject.toJSONString(result));
                } catch (Exception e) {
                    logger.error("-------updateMtOrderFreezedListSync_settle is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前未收货订单
     *
     * @param merId
     * @param day
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderRefundingListSync(Long merId, int day) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        //设置开始时间未90天前
        Integer now = DateUtil.getNowTime();
        mtFindUnReceicedDto.setQueryStartTime(now - 7776000);
        //设置结束时间为day天前
        int endTime = day * 24 * 3600;
        mtFindUnReceicedDto.setQueryEndTime(now - endTime);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderRefundingListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 远程调用订单库API，更新day天前维权中的订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Override
    public void updateMtOrderRefundingListSync(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前维权中订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    updateMtOrder(mtOrder);
                } catch (Exception e) {
                    logger.error("-------updateMtOrderRefundingListSync is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }

    /**
     * 直接结算，更新day天前维权中订单
     *
     * @param merId
     * @param startTime
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateMtOrderRefundingListSync_settle(Long merId, Integer startTime, Integer endTime, Long userId) {
        if (merId == null) {
            return;
        }
        //查询7天前未收货订单
        MtFindUnReceicedDto mtFindUnReceicedDto = new MtFindUnReceicedDto();
        mtFindUnReceicedDto.setMerId(merId);
        mtFindUnReceicedDto.setQueryStartTime(startTime);
        mtFindUnReceicedDto.setQueryEndTime(endTime);
        mtFindUnReceicedDto.setUserId(userId);
        //查询付款状态订单（未收货）
        mtFindUnReceicedDto.setStatus(OrderStatusEnum.STATUS_REFUNDING_VALUE);
        //根据订单返利状态查询
        mtFindUnReceicedDto.setReStatusList(Lists.newArrayList(OrderReStatusEnum.RE_STATUS_NO_VALUE, OrderReStatusEnum.RE_STATUS_FROZEN_VALUE));
        List<MtOrder> mtOrderList = mtOrderMapper.findUnReceivedList(mtFindUnReceicedDto);
        if (mtOrderList != null) {
            for (MtOrder mtOrder : mtOrderList) {
                try {
                    //先修改订单状态为0-付款状态时，才能确认收货
                    mtOrder.setStatus(OrderStatusEnum.STATUS_PAID_VALUE);
                    mtOrder.setUpdateTime(DateUtil.getNowTime());
                    mtOrderMapper.updateStatus(mtOrder);
                    //调用确认收货接口
                    MtOrderSettledDto mtOrderSettledDto = new MtOrderSettledDto();
                    mtOrderSettledDto.setMerId(mtOrder.getMerId());
                    mtOrderSettledDto.setOrderId(mtOrder.getParentOrderNo());
                    mtOrderSettledDto.setChildOrderId(mtOrder.getChildOrderNo());
                    UzaiRespVo<Object> result = mtOrderFeignService.settled(mtOrderSettledDto);
                    logger.info("---发送修改美团订单确认收货-para={}, result={}", JSONObject.toJSONString(mtOrderSettledDto), JSONObject.toJSONString(result));
                } catch (Exception e) {
                    logger.error("-------updateMtOrderUnReceivedListSync_settle is error ordersn={}, error={}", mtOrder.getParentOrderNo(), e.getMessage());
                    continue;
                }
            }
        }
    }


}
